//
//  APPLETextView+Extension.swift
//  123
//
//  Created by pangjiaxing on 16/1/22.
//  Copyright © 2016年 pangjiaxing. All rights reserved.
//

import UIKit

extension APPLETextView{
    func insertEmoyicon(emoticon:APPLEEmoticon){
        if emoticon.isEmoji{
            self.insertText((emoticon.code!as NSString).emoji())
        }else{
            let originalAttr = NSMutableAttributedString(attributedString: self.attributedText)
            let image = UIImage(named: emoticon.fullPath, inBundle: APPLEEmoticonTools.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
            let attachment = APPLEEmoticonTextAttachment()
            attachment.emoticon=emoticon
            attachment.image = image
            let imageWH = self.font?.lineHeight
            attachment.bounds = CGRect(x: 0, y: -3.5, width: imageWH!, height: imageWH!)
            let attr = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            attr.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, 1))


            var range = self.selectedRange
            originalAttr.replaceCharactersInRange(range, withAttributedString: attr)

            self.attributedText = originalAttr

            range.location += 1;range.length = 0
            self.selectedRange = range
            
            // 发送通知
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
            
            // 调用代理身上的方法
            delegate?.textViewDidChange?(self)

        }

    }
    /// 获取到当前输入模型里面的表情字符串
    var emoticonText: String {
        var string = ""
        // [马上有对象]A[带着微博去旅行]
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: []) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? APPLEEmoticonTextAttachment {
                // 代表是图片表情
                string += attachment.emoticon!.chs!
            }else{
                // 代表是文字
                string += (self.attributedText.string as NSString).substringWithRange(range)
            }
        }
        return string
    }

}

